﻿using System;
using System.Web.UI.WebControls;
using MockBusiness;
using MockDataTransferObject;
using MockCommon;
using System.Globalization;
namespace Presentation.AdminPresentation
{
    public partial class Contract : System.Web.UI.Page
    {
        private MessageBusiness _messageBusiness;
        private RoleBusiness _roleBusiness;
        private ContractBusiness _contractBusiness;
        private ConsultantBusiness _consultantBusiness;
        private ContractTypeBusiness _contractTypeBusiness;
        private ClientBusiness _clientBusiness;
        private UserBusiness _userBusiness;
        private Label _warningLabel;
        private Label _errorLabel;
        private Label _successLabel;
        private DropDownList _consultantDropDownList;
        private DropDownList _contractTypeDropDownList;
        private DropDownList _clientDropDownList;
        private DropDownList _dayInWeekDropDownList;
        private TextBox _contentTextBox;
        private TextBox _startDateTextBox;
        private TextBox _endDateTextBox;
        private TextBox _firstNameTextBox;
        private TextBox _lastNameTextBox;
        private TextBox _birthDateTextBox;
        private TextBox _telephone1TextBox;
        private TextBox _telephone2TextBox;
        private TextBox _branchTextBox;
        private TextBox _sortCodeTextBox;
        private RadioButtonList _genderRadioButtonList;
        private Button _addButton;
        private Button _resetButton;

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _messageBusiness = MessageBusiness.RetrieveInstance();
                _roleBusiness = RoleBusiness.RetrieveInstance();
                _contractBusiness = ContractBusiness.RetrieveInstance();
                _consultantBusiness = ConsultantBusiness.RetrieveInstance();
                _clientBusiness = ClientBusiness.RetrieveInstance(true);
                _contractTypeBusiness = ContractTypeBusiness.RetrieveInstance();
                _userBusiness = UserBusiness.RetrieveInstance();
                _warningLabel = (Label)Master.FindControl("WarningLabel");
                _errorLabel = (Label)Master.FindControl("ErrorLabel");
                _successLabel = (Label)Master.FindControl("SuccessLabel");
                _consultantDropDownList = (DropDownList)AddContractUserControl.FindControl("ConsultantDropDownList");
                _contractTypeDropDownList = (DropDownList)AddContractUserControl.FindControl("ContractTypeDropDownList");
                _clientDropDownList = (DropDownList)AddContractUserControl.FindControl("ClientDropDownList");
                _dayInWeekDropDownList = (DropDownList)AddContractUserControl.FindControl("DayInWeekDropDownList");
                _contentTextBox = (TextBox)AddContractUserControl.FindControl("ContentTextBox");
                _startDateTextBox = (TextBox)AddContractUserControl.FindControl("StartDateTextBox");
                _endDateTextBox = (TextBox)AddContractUserControl.FindControl("EndDateTextBox");
                _firstNameTextBox = (TextBox)AddContractUserControl.FindControl("FirstNameTextBox");
                _lastNameTextBox = (TextBox)AddContractUserControl.FindControl("LastNameTextBox");
                _birthDateTextBox = (TextBox)AddContractUserControl.FindControl("BirthDateTextBox");
                _telephone1TextBox = (TextBox)AddContractUserControl.FindControl("Telephone1TextBox");
                _telephone2TextBox = (TextBox)AddContractUserControl.FindControl("Telephone2TextBox");
                _branchTextBox = (TextBox)AddContractUserControl.FindControl("BranchTextBox");
                _sortCodeTextBox = (TextBox)AddContractUserControl.FindControl("SortCodeTextBox");
                _genderRadioButtonList = (RadioButtonList)AddContractUserControl.FindControl("GenderRadioButtonList");
                _addButton = (Button)AddContractUserControl.FindControl("AddButton");
                _resetButton = (Button)AddContractUserControl.FindControl("ResetButton");
                _addButton.Click += new EventHandler(AddButton_Click);
                _resetButton.Click += new EventHandler(ResetButton_Click);
            }
            catch (MockException exception)
            {
                Application["error"] = exception;
                Response.Redirect("../Error.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] != null)
            {
                User user = (User)Session["user"];
                if (user.Role.RoleName == "Admin")
                {
                    if (!IsPostBack)
                    {
                        LoadContract();
                    }
                }
                else
                {
                    Server.Transfer("../NotAuthorized.aspx");
                }
            }
            else
            {
                Response.Redirect("../LogOn.aspx");
            }
            if (IsPostBack)
            {
                _warningLabel.Text = "";
                _errorLabel.Text = "";
                _successLabel.Text = "";
            }
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            try
            {
                //Create consultant
                object consultantId = _consultantDropDownList.Text;
                Consultant consultant = _consultantBusiness.GetById(consultantId);
                //Create contract type
                object contractTypeId = _contractTypeDropDownList.Text;
                ContractType contractType = _contractTypeBusiness.GetById(contractTypeId);
                //Create client
                object clientId = _clientDropDownList.Text;
                Client client = _clientBusiness.GetById(clientId);
                //Create role 
                object roleId = _roleBusiness.GetRoleIdByRoleName("Contractor");
                Role role = _roleBusiness.GetById(roleId);
                //Create user
                Guid userId = Guid.NewGuid();
                string username = _userBusiness.GenerateUserName(_firstNameTextBox.Text, _lastNameTextBox.Text);
                string password = UserBusiness.GeneratePassword();
                User user = new User();
                user.UserId = userId;
                user.UserName = username;
                user.Password = password;
                user.IsActive = true;
                user.Role = role;
                //Create contractor
                Guid contractorId = Guid.NewGuid();
                bool gender = false;
                if (_genderRadioButtonList.SelectedItem.Text == "Male")
                    gender = true;
                int dayInWeek = Int32.Parse(_dayInWeekDropDownList.SelectedValue, CultureInfo.CurrentCulture);
                string firstName = UserBusiness.FormatName(_firstNameTextBox.Text);
                string lastName = UserBusiness.FormatName(_lastNameTextBox.Text);
                Contractor contractor = new Contractor();
                contractor.ContractorId = contractorId;
                contractor.User = user;
                contractor.FirstName = firstName;
                contractor.LastName = lastName;
                contractor.BirthDate = DateTime.Parse(_birthDateTextBox.Text, CultureInfo.CurrentCulture);
                contractor.Gender = gender;
                contractor.Telephone1 = _telephone1TextBox.Text;
                contractor.Telephone2 = _telephone2TextBox.Text;
                contractor.DayInWeek = dayInWeek;
                contractor.Branch = _branchTextBox.Text;
                contractor.SortCode = _sortCodeTextBox.Text;               
                //Create contract
                Guid contractId = Guid.NewGuid();
                MockDataTransferObject.Contract contract = new MockDataTransferObject.Contract();
                contract.ContractId = contractId;
                contract.ContractType = contractType;
                contract.Consultant = consultant;           
                contract.Client = client;
                contract.Contractor = contractor;
                contract.Content = _contentTextBox.Text;
                contract.StartDate = DateTime.Parse(_startDateTextBox.Text, CultureInfo.CurrentCulture);
                contract.EndDate = DateTime.Parse(_endDateTextBox.Text, CultureInfo.CurrentCulture);
                contract.IsActive = true;             
                //Create
                _contractBusiness.Insert(contract);
                Notify(contract);
                _successLabel.Text = "Create a contract successfully!";
                Reset();
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _warningLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void ResetButton_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void LoadContract()
        {
            try
            {
                _clientDropDownList.DataSource = _clientBusiness.RetrieveAllClientUsers();
                _clientDropDownList.DataValueField = "ClientId";
                _clientDropDownList.DataTextField = "Username";
                _clientDropDownList.DataBind();
                _consultantDropDownList.DataSource = _consultantBusiness.RetrieveAllConsultantUsers();
                _consultantDropDownList.DataValueField = "ConsultantId";
                _consultantDropDownList.DataTextField = "Username";
                _consultantDropDownList.DataBind();
                _contractTypeDropDownList.DataSource = _contractTypeBusiness.RetrieveAllContractType();
                _contractTypeDropDownList.DataValueField = "ContractTypeId";
                _contractTypeDropDownList.DataTextField = "ContractTypeName";
                _contractTypeDropDownList.DataBind();
                _genderRadioButtonList.SelectedIndex = 0;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        private void Notify(MockDataTransferObject.Contract contract)
        {
            User fromUser = Session["user"] as User;
            User toUser = contract.Client.User;
            Message message = new Message();
            string contractTypeName = contract.ContractType.ContractTypeName;
            string consultantUsername = contract.Consultant.User.UserName;
            string clientUsername = contract.Client.User.UserName;
            string contractorUsername = contract.Contractor.User.UserName;
            string contentContract = contract.Content;
            string startDate = contract.StartDate.ToString("dd/MM/yyyy hh:mm:ss", CultureInfo.CurrentCulture);
            string endDate = contract.EndDate.ToString("dd/MM/yyyy hh:mm:ss", CultureInfo.CurrentCulture);
            string contractorPassword = contract.Contractor.User.Password;
            string content = @"Dear <b>{0}</b><br/>
                                   Contract has been created for you, some infomations as below:<br/>
                                   <div class=""contentMail"">
                                   -Contract type: <b>{1}</b>.<br/>
                                   -Consultant: <b>{2}</b>.<br/>
                                   -Client: <b>{3}</b>.<br/>
                                   -Contractor: <b>{4}</b>.<br/>
                                   -Contractor password: <b>{5}</b>.<br/>
                                   -Content: <br/>
                                   <b>{6}</b>.<br/>
                                   -Start date: <b>{7}</b>.<br/>
                                   -End date: <b>{8}</b>.<br/>
                                   </div><br/>
                                   Now you can send these information for each contractor of you!<br/><br/>
                                   <b>CMS AutoMailer.</b><br/>
                                   <b>&</b>
                                   <b>Best Regards!</b>";
            message.MessageId = Guid.NewGuid();
            message.From = fromUser;
            message.To = toUser;
            message.Title = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> has created new contract", fromUser.UserName);
            message.Content = String.Format(CultureInfo.CurrentCulture, content, toUser.UserName, contractTypeName, consultantUsername, clientUsername, contractorUsername, contractorPassword, contentContract, startDate, endDate);
            message.IsRead = false;
            message.IsReceive = false;
            message.SendDate = DateTime.Now;
            _messageBusiness.Insert(message);
        }

        private void Reset()
        {
            _birthDateTextBox.Text = "";
            _contentTextBox.Text = "";
            _dayInWeekDropDownList.SelectedIndex = 0;
            _contractTypeDropDownList.SelectedIndex = 0;
            _consultantDropDownList.SelectedIndex = 0;
            _clientDropDownList.SelectedIndex = 0;
            _endDateTextBox.Text = "";
            _firstNameTextBox.Text = "";
            _lastNameTextBox.Text = "";
            _startDateTextBox.Text = "";
            _telephone2TextBox.Text = "";
            _telephone1TextBox.Text = "";
            _branchTextBox.Text = "";
            _sortCodeTextBox.Text = "";
        }
    }
}